"""
  <+DOC STRING+>
"""

import os
import glob
import anydbm
import cPickle

_pool = None
def getPool():
    #TODO: possible thread-safety issue
    global _pool
    if not _pool:
        _pool = _buildPool()
    return _pool

def _isNeedToReBuildDBPool(task_db_file):
    if not os.path.exists(task_db_file):
        return True
    db_mtime = os.path.getmtime(task_db_file)
    for ugtd_file in glob.glob(os.path.join(UGTD_ROOT_PATH, '*.' +
                                            UGTD_FILE_SUFFIX)):
        if os.path.getmtime(ugtd_file)>db_mtime:
            return True
    return False

def _getPoolStat(db):
    if db.has_key('POOLSTAT'):
        return db['POOLSTAT']
    else:
        stat = {'max_index_id':0}
        db['POOLSTAT'] = cPickle.dumps(stat)
        return stat

def _rebuildPool(task_db_file):
    db = anydbm.open(task_db_file, 'c')
    for ugtd_file in glob.glob(os.path.join(UGTD_ROOT_PATH, '*.' +
                                            UGTD_FILE_SUFFIX)):
        if os.path.getmtime(ugtd_file)>db_mtime:
            pass
        pass

def _buildPool():
    """
    rebuild the task db file when necessary
    """
    task_db_file = os.path.join(UGTD_ROOT_PATH, TASK_DB_FILE)
    if _isNeedToReBuildDBPool(task_db_file):
        return _rebuildPool(task_db_file)
    else:
        db = anydbm.open(task_db_file, 'w')
        return db

if __name__ == '__main__':
    pass
